﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RPGMapa.Data;

namespace RPGMapa.Controls
{
    public partial class TilePanel : UserControl
    {
        private Graphics gBB;
        private Graphics gAL;
        private Graphics gCTRL;
        public Graphics gBackBuffer
        {
            get { return gBB; }
        }
        public Graphics gAlphaLayer
        {
            get { return gAL; }
        }
        public Graphics gControl
        {
            get { return gCTRL; }
        }

        private Bitmap backBuffer;
        private Bitmap alphaLayer;
        public Bitmap BackBuffer
        {
            get { return backBuffer; }
            set { backBuffer = value; }
        }
        public Bitmap AlphaLayer
        {
            get { return alphaLayer; }
            set { alphaLayer = value; }
        }

        public TilePanel()
        {
            InitializeComponent();
            CreateGraphicsUtilities(true);
        }

        private void TiledPanel_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawImageUnscaled(backBuffer, Point.Empty);
            e.Graphics.DrawImageUnscaled(alphaLayer, Point.Empty);
        }

        private void TiledPanel_Resize(object sender, EventArgs e)
        {
            Bitmap newBBuffer = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            gBB = Graphics.FromImage(newBBuffer);
            gBB.DrawImage(backBuffer, 0, 0, newBBuffer.Width, newBBuffer.Height);

            backBuffer = newBBuffer;
            gBB = Graphics.FromImage(backBuffer);

            CreateGraphicsUtilities(false);
        }

        private void CreateGraphicsUtilities(bool createBBuffer)
        {
            if (createBBuffer)
            {
                backBuffer = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                gBB = Graphics.FromImage(backBuffer);
                gBB.Clear(Color.SandyBrown);
            }

            alphaLayer = new Bitmap(this.Width, this.Height);
            gAL = Graphics.FromImage(alphaLayer);
            gAL.Clear(Color.Transparent);

            gCTRL = this.CreateGraphics();
        }
    }
}
